package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingPlanDto;
import com.zzyl.entity.NursingPlan;
import com.zzyl.entity.ProjectPlan;
import com.zzyl.mapper.NursingPlanMapper;
import com.zzyl.mapper.NursingProjectPlanMapper;
import com.zzyl.service.NursingPlanService;
import com.zzyl.vo.NursingPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class NursingPlanServiceImpl implements NursingPlanService {

    @Autowired
    private NursingPlanMapper nursingPlanMapper;

    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;

    @Override
    public PageResponse<NursingPlanVo> selectByPage(String name, Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Page page = (Page) nursingPlanMapper.selectByPage(name,status);
        PageResponse<NursingPlanVo> of = PageResponse.of(page, NursingPlanVo.class);
        return of;
    }


    @Override
    public List<NursingPlanVo> selectAll() {
        List<NursingPlanVo> list = nursingPlanMapper.selectByPage("", null);
        return list;
    }

    @Override
    @Transactional
    public void addNursingPlan(NursingPlanDto nursingPlanDto) {
        NursingPlan nursingPlan = BeanUtil.toBean(nursingPlanDto, NursingPlan.class);
        nursingPlan.setStatus(1);
        nursingPlan.setIsDelete(0);
        nursingPlanMapper.insertNursingPlan(nursingPlan);
        for (ProjectPlan projectPlan : nursingPlan.getProjectPlans()) {
            projectPlan.setPlanId(nursingPlan.getId());
        }
        nursingProjectPlanMapper.insertNursingProjectPlans(nursingPlan.getProjectPlans());
    }

    @Override
    public NursingPlanVo selectById(Long id) {
        NursingPlanVo nursingPlanVo= nursingPlanMapper.selectById(id);
        return nursingPlanVo;
    }

    @Override
    @Transactional
    public void updateNursingPlan(Long id,NursingPlanDto nursingPlanDto) {
        NursingPlan nursingPlan = BeanUtil.toBean(nursingPlanDto, NursingPlan.class);
        nursingPlanMapper.updateNursingPlan(nursingPlan);

        //根据护理计划id删除
        nursingProjectPlanMapper.deleteByNursingPlanId(id);

        for (ProjectPlan projectPlan : nursingPlan.getProjectPlans()) {
            projectPlan.setPlanId(id);
        }
        //再添加
        nursingProjectPlanMapper.insertNursingProjectPlans(nursingPlan.getProjectPlans());

    }

    @Override
    public void deleteNursingPlan(Long id) {
        nursingPlanMapper.deleteNursingPlan(id);

        nursingProjectPlanMapper.deleteByNursingPlanId(id);
    }

    @Override
    public void isForbidden(Integer id, Integer status) {
        nursingPlanMapper.updateStatus(id,status);
    }
}
